package com.example.iqiyitest.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.iqiyitest.R;
import com.example.iqiyitest.adapter.DaohangAdapter;
import com.example.iqiyitest.adapter.MovieListAdapter;
import com.example.iqiyitest.adapter.RecyclerAdapter;
import com.example.iqiyitest.base.Constants;
import com.example.iqiyitest.base.RecyclerBaseActivity;
import com.example.iqiyitest.info.FenleiInfo;
import com.example.iqiyitest.info.HomeInfo;
import com.example.iqiyitest.info.MovieDetailInfo;
import com.example.iqiyitest.utils.VideoType;
import com.example.iqiyitest.utils.XsUtils;
import com.example.iqiyitest.view.DurianLoading;
import com.example.iqiyitest.view.MovieView;
import com.example.iqiyitest.view.RadioButtonEx;
import com.example.iqiyitest.view.SmoothRecyclerView;
import com.google.gson.reflect.TypeToken;
import com.iqiyi.movieksdk.sdk.exported.HttpResult;
import com.iqiyi.movieksdk.sdk.exported.IMsgReceiver;
import com.iqiyi.movieksdk.sdk.exported.LogUtils;
import com.iqiyi.movieksdk.sdk.exported.MovieSdk;
import com.iqiyi.movieksdk.sdk.exported.OnResponseListener;
import com.iqiyi.movieksdk.sdk.exported.OrderBy;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ShaixuanActivity extends RecyclerBaseActivity implements IMsgReceiver {
	private ListView typeListView;
	private SubjectTitlesAdapter typeAdapter;
	public ArrayList<HomeInfo> homeInfos = new ArrayList<>();
	public ArrayList<HomeInfo> homeInfostitles = new ArrayList<>();
	private boolean titleHasInit = false;
	private int TYPESKIPINDEX = 1;
	private int TYPEEXTENDINDEX = 0;
	private MovieSdk movieSdk;
	String TAG = "iqiyitest";
	private boolean isScreen = false;
	private String selectTypeName;
	private DurianLoading progressBar;
	private RadioGroup rg_tag;
	private RadioGroup rg_country;
	private RadioGroup rg_year;
	private LinearLayout ll_screen;
	private LinearLayout ll_movies;
	private Map<String, String> screenMap = new HashMap<String, String>();
	private LayoutParams radioButtonParams;
	ArrayList<FenleiInfo> fenleiInfos;
	ArrayList<MovieDetailInfo> movieInfos;
	private int mSelectedItem = -1;
	private static int SCREEN_ANIMATION_DURATION = 300;
	private View selectedTypeView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shaixuan);

		selectTypeName = getIntent().getStringExtra("selectTypeName");
		radioButtonParams = new LayoutParams(LayoutParams.WRAP_CONTENT, (int) getResources().getDimension(R.dimen.d_28));
		typeListView = (ListView) findViewById(R.id.typeListView);
		ll_screen = (LinearLayout) findViewById(R.id.ll_screen);
		ll_movies = (LinearLayout) findViewById(R.id.ll_movies);
		rg_tag = (RadioGroup) findViewById(R.id.rg_tag);

		rg_country = (RadioGroup) findViewById(R.id.rg_country);
		rg_year = (RadioGroup) findViewById(R.id.rg_year);
		rv_movies = (SmoothRecyclerView) findViewById(R.id.rv_movies);
		initRecyclerView();
		progressBar = (DurianLoading) findViewById(R.id.progressBar);
		movieSdk = MovieSdk.init(getApplication(), Constants.serviceUrl, new MovieSdk.OnInitListener() {
			@Override
			public void initOver(int code) {
				Toast.makeText(ShaixuanActivity.this, "init code:" + code, Toast.LENGTH_SHORT).show();
			}
		});
		movieSdk.addMsgReceiver(this);
		typeAdapter = new SubjectTitlesAdapter(this);
		typeListView.setAdapter(typeAdapter);
		typeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) {
				Message msg = new Message();
				msg.arg2 = paramInt;
				msg.obj = paramView;
				changeSelectTypeHandler.sendMessage(msg);
			}

		});
		typeListView.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				int eventAction = event.getAction();
				switch (eventAction) {
				case KeyEvent.ACTION_DOWN: {
					if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
						if (ll_screen.getVisibility() == View.VISIBLE) {
							ll_screen.requestFocus();
						} else if (foucedView != null) {
							foucedView.requestFocusFromTouch();
						} else {
							rv_movies.requestFocusFromTouch();
						}
						return true;
					}
				}
				default:
					break;
				}
				return false;
			}
		});
		initScreen();
	}

	private void fillMovies(HomeInfo type, String tagId, String countryId, String year, int postion) {

		// 筛选
		movieSdk.sdk_listMovieByLabel(tagId, countryId, year, OrderBy.ORDER_XIAZAI, false, 1, 50, new OnResponseListener() {
			@Override
			public void onResponse(HttpResult result) {
				Log.d(TAG, "全部:" + result.data);
				// text.setText(result.data);
				movieInfos = getQuanbuList(result.data);
			}
		});
	}

	private void initMovies() {
		Log.e(TAG, "部署list====" + movieInfos.toString());
		progressBar.hideLoadUi();
		if (movieInfos == null || movieInfos.size() == 0) {
			rv_movies.setVisibility(View.GONE);
			return;
		}
		rv_movies.setVisibility(View.VISIBLE);
		RecyclerAdapter ra = null;
		if (rv_movies.getAdapter() != null) {
			rv_movies.scrollToPosition(0);
			ra = (RecyclerAdapter) rv_movies.getAdapter();
			ra.setMovies(movieInfos);
			ra.notifyDataSetChanged();
		} else {
			ra = new RecyclerAdapter(this, movieInfos);
			ra.setIconFocusChangeListener(new MovieView.MovieFocusChangeListener() {

				@Override
				public void onFocusChange(MovieView v, boolean focus) {
					if (focus) {
						foucedView = v;
						int index = foucedView.getIndex();
						loadPage(index + columnNum * 3);
						foucedView.setId(View.generateViewId());
						// tv_index.setText(String.valueOf(index + 1));
						if (index % columnNum == 0) {
							isMovieViewInMaxLeft = true;
						} else {
							isMovieViewInMaxLeft = false;
						}
						if (index < columnNum) {
							if (isScreen) {
								showScreenView();
								foucedView.setNextFocusUpId(currYearId);
							} else {
								// foucedView.setNextFocusUpId(btn_search.getId());
							}
						} else if (isScreen) {
							hideScreenView();
						}
						if ((movieInfos.size() - index) <= (movieInfos.size() % columnNum)) {
							foucedView.setNextFocusDownId(foucedView.getId());
						}
						if (movieInfos.size() == (index + 1)) {
							foucedView.setNextFocusRightId(foucedView.getId());
						}
					}
				}
			});
			ra.setItemOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					MovieDetailInfo movie = ((MovieView) v).getMovie();
					if (movie != null && !XsUtils.isNull(movie.getQipuId() + "")) {
						showDetail(movie);
					}
				}
			});
			ra.setItemOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View view, int keyCode, KeyEvent event) {
					if (isMovieViewInMaxLeft && keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
						typeListView.setFocusable(true);
						typeListView.setSelection(mSelectedItem);
						typeListView.requestFocusFromTouch();
						return true;
					} else {
						typeListView.setFocusable(false);
					}
					return false;
				}
			});
			rv_movies.setAdapter(ra);
		}
	}

	private void showDetail(MovieDetailInfo movieDetailInfo) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(ShaixuanActivity.this, DetailForMovieActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", movieDetailInfo);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private void hideScreenView() {
		if (ll_screen.getVisibility() != View.VISIBLE)
			return;
		int h = ll_screen.getHeight();
		AnimatorSet animatorSet = new AnimatorSet();// 组合动画
		ObjectAnimator scaleY = ObjectAnimator.ofFloat(ll_screen, "y", 0f, -h);
		ObjectAnimator scaleY2 = ObjectAnimator.ofFloat(ll_movies, "y", h, 0f);
		animatorSet.setDuration(SCREEN_ANIMATION_DURATION);
		animatorSet.setInterpolator(new DecelerateInterpolator());
		animatorSet.play(scaleY).with(scaleY2);// 两个动画同时开始
		animatorSet.start();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				ll_screen.setVisibility(View.INVISIBLE);
			}
		}, 500);
	}

	private void showScreenView() {
		if (ll_screen.getVisibility() == View.VISIBLE)
			return;
		ll_screen.setVisibility(View.VISIBLE);
		int h = ll_screen.getHeight();
		AnimatorSet animatorSet = new AnimatorSet();// 组合动画
		ObjectAnimator scaleY = ObjectAnimator.ofFloat(ll_screen, "y", -h, 0f);
		ObjectAnimator scaleY2 = ObjectAnimator.ofFloat(ll_movies, "y", 0f, h);
		animatorSet.setDuration(SCREEN_ANIMATION_DURATION);
		animatorSet.setInterpolator(new DecelerateInterpolator());
		animatorSet.play(scaleY).with(scaleY2);// 两个动画同时开始
		animatorSet.start();
	}

	public ArrayList<MovieDetailInfo> getQuanbuList(String data) {
		JSONObject jsonObject;
		MovieDetailInfo movieDetailInfo;
		String data_item;
		ArrayList<MovieDetailInfo> movieInfos_old;
		movieInfos_old = new ArrayList<MovieDetailInfo>();
		try {
			jsonObject = new JSONObject(data);
			JSONArray jsonArray = jsonObject.getJSONArray("result");
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				movieDetailInfo = new MovieDetailInfo();
				movieDetailInfo.setPosterLocalImg(jsonObject.optString("posterLocalImg"));
				movieDetailInfo.setDuration(jsonObject.optInt("duration"));
				movieDetailInfo.setShotDesc(jsonObject.optString("shotDesc"));
				movieDetailInfo.setDescription(jsonObject.optString("description"));
				movieDetailInfo.setScore(jsonObject.optInt("score"));
				movieDetailInfo.setShowTime(jsonObject.optInt("showtime"));
				movieDetailInfo.setPlayType(jsonObject.optString("playType"));
				movieDetailInfo.setPlayTimes(jsonObject.optInt("playTimes"));
				movieDetailInfo.setActor(jsonObject.optString("actor"));
				movieDetailInfo.setQipuId(jsonObject.optInt("qipuId"));
				movieDetailInfo.setDirector(jsonObject.optString("director"));
				movieDetailInfo.setDisplayName(jsonObject.optString("displayName"));
				movieDetailInfo.setVideoType(jsonObject.optString("videoType"));
				movieInfos_old.add(movieDetailInfo);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread() {
			public void run() {
				Log.e(TAG, "3333333333333333333333");
				Message m = new Message();
				m.what = 2;
				splashHandler.sendMessage(m);

			}
		}.start();
		return movieInfos_old;
	}

	/*
	 * 
	 * 左侧标题栏
	 */
	public class SubjectTitlesAdapter extends BaseAdapter {
		private LayoutInflater mInflater = null;
		private SparseArray<View> views = new SparseArray<View>();

		private SubjectTitlesAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return homeInfostitles.size() + TYPESKIPINDEX + TYPEEXTENDINDEX;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public View getView(int position) {
			if (position < 0 || position > views.size()) {
				return null;
			}
			return views.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LogUtils.d("position:" + position + ";" + (convertView == null));
			if (views.get(position) == null) {
				View view = mInflater.inflate(R.layout.subject_title_item, null);
				views.put(position, view);
			}
			convertView = views.get(position);
			TextView typeTextView = (TextView) convertView.findViewById(R.id.typeTextView);
			if (position == 0) {
				typeTextView.setText(" 筛 选");
				convertView.setTag("screen");
				Drawable drawable = null;
				drawable = getResources().getDrawable(R.drawable.screen);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				typeTextView.setCompoundDrawables(drawable, null, null, null);
				// } else if (position == (getCount()-1)) {
				// convertView.setId(View.generateViewId());
				// convertView.setNextFocusDownId(convertView.getId());
				// typeTextView.setText("更多应用");
				// convertView.setTag("app");
			} else {
				convertView.setTag("movie");
				typeTextView.setText(homeInfostitles.get(position - TYPESKIPINDEX).getName());
				typeTextView.setCompoundDrawables(null, null, null, null);
			}
			return convertView;
		}

	}

	private RadioButtonEx rb_tag_all;
	private RadioButtonEx rb_country_all;
	private RadioButtonEx rb_year_all;
	private int currTagId = -1;
	private int currCountryId = -1;
	private int currYearId = -1;

	private void initScreen() {
		rb_tag_all = createRadioButtonEx("", "全部", tagCheckedChangeListener, tagFocusChangeListener);
		// rg_tag.addView(rb_tag_all, radioButtonParams);
		rb_country_all = createRadioButtonEx("", "全部", countryCheckedChangeListener, countryFocusChangeListener);
		// rg_country.addView(rb_country_all, radioButtonParams);
		rb_year_all = createRadioButtonEx("", "全部", yearCheckedChangeListener, yearFocusChangeListener);
		// rg_year.addView(rb_year_all, radioButtonParams);
		currTagId = rb_tag_all.getId();
		currCountryId = rb_country_all.getId();
		currYearId = rb_year_all.getId();
		rb_tag_all.setNextFocusLeftId(typeListView.getId());
		rb_country_all.setNextFocusLeftId(typeListView.getId());
		rb_year_all.setNextFocusLeftId(typeListView.getId());
		movieSdk.sdk_movieLabel(new OnResponseListener() {
			@Override
			public void onResponse(HttpResult result) {
				Log.d(TAG, "分类" + result.data);
				// text.setText(result.data);
				fenleiInfos = getFenleiList(result.data);
				Log.d(TAG, "分类111111111111111" + fenleiInfos.toString());
			}
		});
	}

	public ArrayList<FenleiInfo> getFenleiList(String data) {
		JSONObject jsonObject;
		FenleiInfo fenleiInfo;
		ArrayList<String> datas;
		String data_item;
		ArrayList<FenleiInfo> fenleiInfos_old;
		fenleiInfos_old = new ArrayList<FenleiInfo>();
		try {
			jsonObject = new JSONObject(data);
			JSONArray jsonArray = jsonObject.getJSONArray("cate");
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				fenleiInfo = new FenleiInfo();
				fenleiInfo.setType(jsonObject.optString("type"));
				fenleiInfo.setName(jsonObject.optString("name"));
				JSONArray jsonArray2 = jsonObject.getJSONArray("data");
				datas = new ArrayList<String>();
				for (int j = 0; j < jsonArray2.length(); j++) {
					data_item = jsonArray2.get(j).toString();
					datas.add(data_item);
				}
				fenleiInfo.setData(datas);
				fenleiInfos_old.add(fenleiInfo);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread() {
			public void run() {
				Log.e(TAG, "1111222222222222222222222222222");
				Message m = new Message();
				m.what = 1;
				splashHandler.sendMessage(m);

			}
		}.start();
		return fenleiInfos_old;
	}

	private Handler splashHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Log.e(TAG, "11111111111111111111111111," + fenleiInfos.get(0).getData());
				ArrayList<String> nameInfos = new ArrayList<>();
				nameInfos = fenleiInfos.get(0).getData();
				if (nameInfos != null && !nameInfos.isEmpty()) {
					for (String tag : nameInfos) {
						RadioButtonEx rb = createRadioButtonEx(tag, tag, tagCheckedChangeListener, tagFocusChangeListener);
						rb.setNextFocusDownId(rb_country_all.getId());
						rg_tag.addView(rb, radioButtonParams);
					}
				}
				ArrayList<String> contryInfos = new ArrayList<>();
				contryInfos = fenleiInfos.get(1).getData();
				if (contryInfos != null && !contryInfos.isEmpty()) {
					for (String country : contryInfos) {
						RadioButtonEx rb = createRadioButtonEx(country, country, countryCheckedChangeListener, countryFocusChangeListener);
						rb.setNextFocusDownId(rb_year_all.getId());
						rg_country.addView(rb, radioButtonParams);
					}
				}
				ArrayList<String> yearInfos = new ArrayList<>();
				yearInfos = fenleiInfos.get(2).getData();
				if (yearInfos != null && !yearInfos.isEmpty()) {
					for (String year : yearInfos) {
						RadioButtonEx rb = null;
						if ("-1".equals(year)) {
							continue;
						} else {
							rb = createRadioButtonEx(year, year, yearCheckedChangeListener, yearFocusChangeListener);
						}
						rg_year.addView(rb, radioButtonParams);
					}
				}
				break;

			case 2:
				initMovies();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@SuppressWarnings("deprecation")
	private RadioButtonEx createRadioButtonEx(String id, String name, OnCheckedChangeListener checkedChangeListener, OnFocusChangeListener focusChangeListener) {
		RadioButtonEx rb = new RadioButtonEx(ShaixuanActivity.this);
		rb.setId(View.generateViewId());
		rb.setBackground(getResources().getDrawable(R.drawable.screen_selector));
		rb.setGravity(Gravity.CENTER);
		rb.setTag(id);
		rb.setText(name);
		rb.setTextColor(getResources().getColor(R.color.white));
		int textSize = (int) getResources().getDimension(R.dimen.d_20);
		rb.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
		Bitmap a = null;
		rb.setButtonDrawable(new BitmapDrawable(a));
		rb.setOnCheckedChangeListener(checkedChangeListener);
		rb.setOnFocusChangeListener(focusChangeListener);
		return rb;
	}

	private void refreshMoviesByScreen() {
		progressBar.showLoadUi();
		fillMovies(null, screenMap.get("tagId"), screenMap.get("countryId"), screenMap.get("year"), 0);
	}

	private void initTitleList() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		String url = Constants.serviceUrl;

		movieSdk.sdk_homePage(1, 50, new OnResponseListener() {
			@Override
			public void onResponse(HttpResult result) {
				Log.d(TAG, result.toString());
				Log.d(TAG, result.data);
				JSONArray jsonArray;
				MovieDetailInfo movieDetailInfo;
				homeInfos = new ArrayList<>();
				
				try {
					jsonArray = new JSONArray(result.data);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject;
						HomeInfo homeInfo = new HomeInfo();
						jsonObject = jsonArray.getJSONObject(i);
						Log.e("分类111111", jsonObject.toString());
						homeInfo.setName(jsonObject.optString("name"));
						homeInfo.setId(jsonObject.optString("id"));
						ArrayList<MovieDetailInfo> movieDetailInfos = new ArrayList<>();
						JSONArray jsonArray2 = jsonObject.getJSONArray("episodes");
						Log.e("首页333333", jsonArray2.toString());
						for (int j = 0; j < jsonArray2.length(); j++) {
							JSONObject jsonObject2;
							jsonObject2 = jsonArray2.getJSONObject(j);
							Log.e("首页4444444444444", jsonObject2.toString());
							movieDetailInfo = new MovieDetailInfo();
							movieDetailInfo.setPosterLocalImg(jsonObject2.optString("posterLocalImg"));
							movieDetailInfo.setScore(jsonObject2.optInt("score"));
							movieDetailInfo.setPlayType(jsonObject2.optString("playType"));
							movieDetailInfo.setShotDesc(jsonObject2.optString("shotDesc"));
							movieDetailInfo.setQipuId(jsonObject2.optInt("qipuId"));
							movieDetailInfo.setDisplayName(jsonObject2.optString("displayName"));
							movieDetailInfo.setVideoType(jsonObject2.optString("videoType"));
							movieDetailInfos.add(movieDetailInfo);
						}
						homeInfo.setEpisodes(movieDetailInfos);
						homeInfos.add(homeInfo);
						homeInfostitles.add(homeInfo);
						typeAdapter.notifyDataSetChanged();

						if (homeInfos != null && !homeInfos.isEmpty()) {
							int typeIndex = 0;
							if (!XsUtils.isNull(selectTypeName)) {
								for (int p = 0; p < homeInfos.size(); p++) {
									if (selectTypeName.equals(homeInfos.get(p).getName())) {
										typeIndex = p;
										break;
									}
								}
							}
							int position = TYPESKIPINDEX + typeIndex;
							changeSelectTypeHandler.removeMessages(0);
							Message msg = new Message();
							msg.arg2 = position;
							changeSelectTypeHandler.sendMessageDelayed(msg, 500);
							titleHasInit = true;
						}

						scollHandler.sendEmptyMessageDelayed(0, 5000);
						titleHasInit = true;
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		typeListView.requestFocus();
	}

	private Handler scollHandler = new Handler() {
		public void handleMessage(Message msg) {
			typeListView.scrollTo(0, 0);
		};
	};

	@Override
	protected void onResume() {
		if (!titleHasInit) {
			initTitleList();
		}
		super.onResume();
	}

	private Handler changeSelectTypeHandler = new Handler() {
		public void handleMessage(Message msg) {
			int position = msg.arg2;
			View paramView = null;
			if (msg.obj != null && msg.obj instanceof View) {
				paramView = (View) msg.obj;
			} else {
				paramView = typeAdapter.getView(position);
			}
			String tag = null;
			if (paramView != null) {
				tag = (String) paramView.getTag();
			}
			Drawable drawable = null;
			isScreen = false;
			// if ("search".equals(tag)) {
			// showSearch(paramView);
			// return;
			// } else

			if ("screen".equals(tag)) {
				drawable = getResources().getDrawable(R.drawable.screen_selected);
				isScreen = true;
				showScreenView();
				mSelectedItem = -1;
				fillMovies(null, "全部", "全部", "全部", 0);
			} else {
				hideScreenView();
				refreshMovies(position);// position 最新热播为1，最新上线为2
				Log.e("tanfen", "position:" + position);
			}
			if (selectedTypeView != null) {
				TextView tv = (TextView) selectedTypeView.findViewById(R.id.typeTextView);
				tv.setTextColor(getResources().getColor(R.color.text_type));
				String oldTag = (String) selectedTypeView.getTag();
				Drawable oldDrawable = null;
				if ("screen".equals(oldTag)) {
					oldDrawable = getResources().getDrawable(R.drawable.screen);
				}
				if (oldDrawable != null) {
					oldDrawable.setBounds(0, 0, oldDrawable.getMinimumWidth(), oldDrawable.getMinimumHeight());
					tv.setCompoundDrawables(oldDrawable, null, null, null);
				}
			}
			selectedTypeView = paramView;
			TextView tv = (TextView) selectedTypeView.findViewById(R.id.typeTextView);
			tv.setTextColor(getResources().getColor(R.color.text_type_selected));
			if (drawable != null) {
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				tv.setCompoundDrawables(drawable, null, null, null);
			}

		};
	};

	private void refreshMovies(int typeIndex) {
		progressBar.showLoadUi();
		foucedView = null;
		if ((homeInfos.size() + TYPESKIPINDEX) <= typeIndex || mSelectedItem == typeIndex) {
			progressBar.hideLoadUi();
			return;
		}

		int index = typeIndex - TYPESKIPINDEX;
		if (index < 0 || index > homeInfos.size()) {
			return;
		}
		try {
			if (typeListView.getAdapter() != null && typeListView.getAdapter().getCount() > typeIndex) {
				typeListView.setSelection(typeIndex);
			}
		} catch (Exception e) {
		}
		HomeInfo type = homeInfos.get(index);
		// fillMovies(type, "全部", "全部", "全部", typeIndex);
		loadListData(typeIndex);
		mSelectedItem = typeIndex;
	}

	private void loadListData(final int typeIndex) {
		movieSdk.sdk_homePage(1, 50, new OnResponseListener() {
			@Override
			public void onResponse(HttpResult result) {
				Log.d(TAG, result.toString());
				Log.d(TAG, result.data);
				JSONArray jsonArray;
				MovieDetailInfo movieDetailInfo;
				homeInfos = new ArrayList<>();
//				homeInfos.clear();
			Log.e("tanfen", "拉取数据1111"+typeIndex);
				try {
					jsonArray = new JSONArray(result.data);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject;
						HomeInfo homeInfo = new HomeInfo();
						jsonObject = jsonArray.getJSONObject(i);
						homeInfo.setName(jsonObject.optString("name"));
						homeInfo.setId(jsonObject.optString("id"));
						ArrayList<MovieDetailInfo> movieDetailInfos = new ArrayList<>();
						JSONArray jsonArray2 = jsonObject.getJSONArray("episodes");
						for (int j = 0; j < jsonArray2.length(); j++) {
							JSONObject jsonObject2;
							jsonObject2 = jsonArray2.getJSONObject(j);
							movieDetailInfo = new MovieDetailInfo();
							movieDetailInfo.setPosterLocalImg(jsonObject2.optString("posterLocalImg"));
							movieDetailInfo.setScore(jsonObject2.optInt("score"));
							movieDetailInfo.setPlayType(jsonObject2.optString("playType"));
							movieDetailInfo.setShotDesc(jsonObject2.optString("shotDesc"));
							movieDetailInfo.setQipuId(jsonObject2.optInt("qipuId"));
							movieDetailInfo.setDisplayName(jsonObject2.optString("displayName"));
							movieDetailInfo.setVideoType(jsonObject2.optString("videoType"));
							movieDetailInfos.add(movieDetailInfo);
						}
						homeInfo.setEpisodes(movieDetailInfos);
						homeInfos.add(homeInfo);
						scollHandler.sendEmptyMessageDelayed(0, 5000);
						titleHasInit = true;
					}
					
					
					Log.e("tanfen", "拉取数据"+homeInfos.size());
					movieInfos=new ArrayList<>();
					movieInfos.clear();
					movieInfos = homeInfos.get(typeIndex-1).getEpisodes();

					new Thread() {
						public void run() {
							Log.e(TAG, "3333333333333333333333");
							Message m = new Message();
							m.what = 2;
							splashHandler.sendMessage(m);

						}
					}.start();
					

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		typeListView.requestFocus();
	}

	OnCheckedChangeListener tagCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton paramCompoundButton, boolean paramBoolean) {
			if (paramBoolean) {
				currTagId = paramCompoundButton.getId();
				if (paramCompoundButton.getTag() == null || "".equals((String) paramCompoundButton.getTag())) {
					if (screenMap.get("tagId") != null) {
						screenMap.remove("tagId");
						refreshMoviesByScreen();
					}
				} else {
					if (screenMap.get("tagId") == null || !screenMap.get("tagId").equals((String) paramCompoundButton.getTag())) {
						screenMap.put("tagId", (String) paramCompoundButton.getTag());
						refreshMoviesByScreen();
					}
				}
			}
		}
	};
	OnCheckedChangeListener countryCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton paramCompoundButton, boolean paramBoolean) {
			if (paramBoolean) {
				currCountryId = paramCompoundButton.getId();
				if (paramCompoundButton.getTag() == null || "".equals((String) paramCompoundButton.getTag())) {
					if (screenMap.get("countryId") != null) {
						screenMap.remove("countryId");
						refreshMoviesByScreen();
					}
				} else {
					if (screenMap.get("countryId") == null || !screenMap.get("countryId").equals((String) paramCompoundButton.getTag())) {
						screenMap.put("countryId", (String) paramCompoundButton.getTag());
						refreshMoviesByScreen();
					}
				}
			}
		}
	};
	OnCheckedChangeListener yearCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton paramCompoundButton, boolean paramBoolean) {
			if (paramBoolean) {
				currYearId = paramCompoundButton.getId();
				if (paramCompoundButton.getTag() == null || "".equals((String) paramCompoundButton.getTag())) {
					if (screenMap.get("year") != null) {
						screenMap.remove("year");
						refreshMoviesByScreen();
					}
				} else {
					if (screenMap.get("year") == null || !screenMap.get("year").equals((String) paramCompoundButton.getTag())) {
						screenMap.put("year", (String) paramCompoundButton.getTag());
						refreshMoviesByScreen();
					}
				}
			}
		}
	};

	OnFocusChangeListener yearFocusChangeListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View paramView, boolean paramBoolean) {
			if (paramBoolean) {
				paramView.setNextFocusUpId(currCountryId);
				paramView.setNextFocusDownId(getFirstMovieViewId());
				typeListView.setFocusable(true);
			}
		}
	};
	OnFocusChangeListener countryFocusChangeListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View paramView, boolean paramBoolean) {
			if (paramBoolean) {
				paramView.setNextFocusUpId(currTagId);
				paramView.setNextFocusDownId(currYearId);
				typeListView.setFocusable(true);
			}
		}
	};
	OnFocusChangeListener tagFocusChangeListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View paramView, boolean paramBoolean) {
			if (paramBoolean) {
				paramView.setNextFocusDownId(currCountryId);
				typeListView.setFocusable(true);
			}
		}
	};

	private int getFirstMovieViewId() {
		int count = rv_movies.getChildCount();
		if (count > 0) {
			return rv_movies.getChildAt(0).getId();
		}
		return -1;
	}

	@Override
	public void onReceived(final String s) {
		Toast.makeText(this, "msg:" + s, Toast.LENGTH_SHORT).show();
		Log.d(TAG, "msg" + s);
	}
}
